import $tools from "./tools.js";
import $var from "./var.js";
import $fun from "./fun.js";
import $skip from "./skip.js";

var loading = false;

var getAuthInfo = function() {
	let auth_info = $fun.getCache('auth_info');
	let user_info = $fun.getCache('user_info');
	let info = {
		uid: user_info && user_info ? user_info.uid : '',
		token: auth_info || '',
	};
	let time = new Date().getTime();
	// console.log(auth_info)
	return {
		authorization: $tools.AES.encrypt(JSON.stringify(info), $var.miyao.a,time + 'abc'),
		token: auth_info ? auth_info : '',
		time: time,
		deviceId: $var.deviceId,
		lang: $var.lang
	};
}

//通信 GET
async function $get(params) {
	return new Promise((resolve) => {
		if (params.loading) {
			uni.showLoading({
				title: '',
				mask: true
			});
			loading = true;
		}
		let authInfo = getAuthInfo();
		// console.log(authInfo)
		if(params.url.indexOf('://') === -1){
			params.url = $var.apiUrl + params.url;
		}
		uni.request({
			url: params.url, //接口地址。
			data: params.data || {}, //接口get参数
			method: "GET",
			header: {
				// "content-type": 'application/json;charset:utf-8;',
				"content-type": 'application/x-www-form-urlencoded;charset=UTF-8',
				...authInfo
			},
			success: (resp) => {
				if (loading) {
					uni.hideLoading();
					loading = false;
				}
				if (resp.statusCode != 200) {
					uni.showToast({
						title: 'fail',
						icon: 'error',
						duration: 2000
					});
				}
				resp = resp.data;
				setDefaultInfo(resp); //设置令牌
				if (params.fun) { //自定义方法 - 单独执行
					params.fun(resp, params._this);
					return false;
				}
				progress(params, resp) //统一处理
				setTimeout(() => uni.stopPullDownRefresh(), 618);
				resolve(resp); //结束
			},
			fail: (resp) => {
				console.log('fail',resp);
			}
		});
	});

}





//通信 POST
async function $post(params) {
	return new Promise((resolve) => {
		var requestData = {};
		if (params.data) requestData = Object.assign(requestData, params.data);
		if ($var.encrypt) {
			requestData = {
				encrypt_data: $tools.AES.encrypt(JSON.stringify(requestData), $var.miyao.a, $var.miyao
					.b)
			};
		}
		if (params.loading === undefined || params.loading) {
			uni.showLoading({
				title: '',
				mask: true
			});
			loading = true;
		}
		params.type = params.type || 'POST';
		console.log(params.type + '通信：' + $var.apiUrl + params.url, requestData);
		if(params.url.indexOf('://') === -1){
			params.url = $var.apiUrl + params.url;
		}
		let authInfo = getAuthInfo();
		uni.request({
			url: params.url, //仅为示例，并非真实接口地址。
			data: requestData,
			method: params.type,
			header: {
				"content-type": 'application/x-www-form-urlencoded;charset=UTF-8',
				// "content-type": 'application/json;charset:utf-8;',
				...authInfo
			},
			success: (resp) => {
				if (loading) {
					uni.hideLoading();
					loading = false;
				}
				if (resp.statusCode != 200) {
					uni.showToast({
						title: resp.statusCode.toString(),
						icon: 'error',
						duration: 3500,
						mask: true
					});
					resolve(); //结束
				}
				resp = resp.data;
				console.log(resp);
				setDefaultInfo(resp); //设置令牌
				if (params.fun) { //自定义方法 - 单独执行
					params.fun(resp, params._this);
					return false;
				}
				progress(params, resp) //统一处理
				resolve(); //结束
			},
			fail: (resp) => {
				uni.showToast({
					icon: 'error',
					title: resp.errMsg,
					mask: false,
					duration: 3500
				});
			}
		});
	});

}


function setDefaultInfo(r) {
	if (r.user_info) {
		$fun.setCache('user_info', r.user_info)
		uni.$emit('changeUserInfo',r.user_info);
	}
	if (r.auth_info) {
		$fun.setCache('auth_info', r.auth_info)
	} else if (r.login_status === false) {
		$fun.setCache('user_info', null)
		$fun.setCache('auth_info', null)
	}
}

function progress(params, resp) {
	//自定义方法 - 前置执行
	params.beforeFun && params.beforeFun(resp, params._this);
	//自动修改页面数据
	if (params._this) {
		if (params.key) {
			params._this[params.key] = resp;
		} else {
			for (var index in resp) params._this[index] = resp[index];
		}
	}

	var waitTime = resp.waitTime || 3000; //设置提示信息等待时间

	if (resp.error) { //错误信息
		uni.showToast({
			icon: 'none',
			title: resp.error,
			mask: true,
			duration: 3000,
			success() {
				setTimeout(() => {
					let str = params.skipParams || '';
					let skipStr = '';
					if (resp.skip) {
						 skipStr = resp.skip;
					} else if (params.skip) {
						skipStr = params.skip;
					}else{
						return;
					}
					skipStr = !str ? skipStr : skipStr + '?' + str;
					$skip.to(skipStr);
				}, waitTime)
				// setTimeout(() => { resp.skip && $skip.to(resp.skip); }, waitTime)
			}
		})
		// uni.showModal({
		// 	title: '提示',
		// 	content: '这是一个模态弹窗',
		// 	success: function (res) {
		// 		if (res.confirm) {
		// 			console.log('用户点击确定');
		// 		} else if (res.cancel) {
		// 			console.log('用户点击取消');
		// 		}
		// 	}
		// });
	} else if (resp.msg) { //信息提示
		uni.showToast({
			icon: 'none',
			title: resp.msg,
			mask: true,
			duration: 2600,
			success() {
				console.log(resp)
				setTimeout(() => {
					let str = params.skipParams || '';
					let skipStr = '';
					if (resp.skip) {
						skipStr = resp.skip;
					} else if (params.skip) {
						skipStr = params.skip;
					}else{
						return;
					}
					skipStr = !str ? skipStr : skipStr + '?' + str;
					$skip.to(skipStr);
				}, waitTime)
			}
		})
	} else if (resp.skip) {
		$skip.to(resp.skip);
	}
	//自定义方法 - 最后执行
	if (params.afterFun) params.afterFun(resp, params._this);
}

// 暴露属性和方法
export default {
	$get,
	$post,
	getAuthInfo
};